<template>
  <div>
    <v-header></v-header>
    <div class="line"></div>
    <!--导航栏-->
    <v-menu></v-menu>
    <!--主体-->
    <div style="overflow:hidden">
      <div class="cover" :style="{height:windowHeight+'px'}"></div>
      <div class="cover1" :style="{backgroundImage:`url(${musicInfo.img})`,height:windowHeight+'px'}" ></div>
      <div class="playMusicBody">
        <!--宽度为1000px的中心位置-->
        <div class="musicBody">
          <el-row>
            <!--图片显示区域-->
            <el-col :span="12">
              <div style="text-align: center;margin-top: 20px">
                <el-link :underline="false" v-show="true">
                  <el-image
                    style="width: 200px; height: 200px"
                    :src="musicInfo.img"
                    fit="fill"
                    placeholder></el-image>
                </el-link>
              </div>
            </el-col>
            <!--歌词显示区域-->
            <el-col :span="12">
              <div style="text-align: left;margin-top: 20px">
                <div>
                  <h3 class="textColor_1">{{musicInfo.songName}}</h3>
                  <el-row>
                    <el-col :span="12">
                      <div class="textColor_2">专辑名: &nbsp;<span class="textColor_1">{{musicInfo.albumName}}</span></div>
                    </el-col>
                    <el-col :span="12">
                      <div class="textColor_2">歌手: &nbsp;<span class="textColor_1">{{musicInfo.authorName}}</span></div>
                    </el-col>
                  </el-row>
                  <div style="height: 350px;margin-top: 40px" id="scrollbar">
                    <el-scrollbar class="textColor_2" style="z-index: 3">
                      <div>
                        <ul class="lyric" ref="lyric">
                          <!--改成==,===不生效-->
                          <li v-for="(item,key) in audio.currentMusicLyric"
                              :class="{each:true, choose: (key == audio.lyricIndex)}" :id="key">
                            {{item}}
                          </li>
                        </ul>
                      </div>
                    </el-scrollbar>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <!--底部播放组件位置-->
    <div class="player" style="z-index: 4">
      <audio
        :src="musicInfo.playUrl"
        ref="audio"
        @error="onError"
        @timeupdate="onTimeUpdate"
        @loadedmetadata="onLoadedMetaData"
        autoplay
        @ended="nextMusic"></audio>
      <div class="musicBody" style="vertical-align: middle;">
        <el-row :gutter="10">
          <!--播放按钮区域-->
          <el-col :span="6">
            <div style="height: 100%">
              <el-row>
                <!--上一首-->
                <el-col :span="8">
                  <div>
                    <el-link @click="lastMusic"><i class="iconfont icon-shangyishoushangyige playIconSize"></i>
                    </el-link>
                  </div>
                </el-col>
                <!--暂停和播放-->
                <el-col :span="8">
                  <div>
                    <el-link @click="onPlay" v-if="audio.playing === false">
                      <i class="iconfont icon-bofangsanjiaoxing playIconSize"></i>
                    </el-link>
                    <el-link @click="onPause" v-else>
                      <i class="iconfont icon-zanting playIconSize"></i>
                    </el-link>
                  </div>
                </el-col>
                <!--下一首-->
                <el-col :span="8">
                  <div>
                    <el-link @click="nextMusic"><i class="iconfont icon-xiayigexiayishou playIconSize"></i></el-link>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-col>
          <!--歌曲进度条和专辑封面区域-->
          <el-col :span="11">
            <el-row>
              <el-col :span="4">
                <div>
                  <el-link :underline="false" v-show="true">
                    <el-image
                      style="width: 60px; height: 60px;margin-top: 10px"
                      :src="musicInfo.img"
                      fit="fill"
                      placeholder></el-image>
                  </el-link>
                </div>
              </el-col>
              <el-col :span="20">
                <div class="disablePlayer">
                  <div>
                    <div style="width: 300px;display: inline-block;margin-top: 10px">
                      <span style="width: 200px">{{musicInfo.songName}}</span>
                    </div>
                    <span style="margin-right: 0">{{audio.showNowTime}}/{{audio.showTimeLength}}</span>
                    <el-slider v-model="sliderTime" @change="changeCurrentTime"></el-slider>
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-col>
          <!--喜欢、分享、播放列表、播放顺序、声音调节、评论-->
          <el-col :span="7">
            <el-row>
              <!--喜欢-->
              <el-col :span="6" style="text-align: center">
                <el-link @click="likeMusic(hash,albumId)">
                  <div v-if="musicInfo.likeFlag === 0">
                    <i class="iconfont icon-xin iconSize"></i>
                  </div>
                  <div v-else>
                    <i class="iconfont icon-xin2 iconSize" style="color: red"></i>
                  </div>
                </el-link>
              </el-col>
              <!--评论-->
              <el-col :span="6" style="text-align: center">
                <div>
                  <el-link @click="toPlayMusicComment"><i class="iconfont icon-xiaoxi iconSize"></i></el-link>
                </div>
              </el-col>
              <!--播放列表-->
              <el-col :span="6" style="text-align: center">
                <div>
                  <el-link><i class="iconfont icon-shuxingliebiaoxiangqing iconSize" title="播放列表"
                              @click="openMusicPlayQueue"></i></el-link>
                </div>
              </el-col>
              <!--分享歌曲-->
              <el-col :span="6" style="text-align: center">
                <div>
                  <el-link @click="copyShare"><i class="iconfont icon-fenxiang iconSize"></i></el-link>
                </div>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </div>
    <!--播放列表绝对定位-->
    <el-card class="box-card" :style="'display:'+display">
      <template #header>
        <div class="card-header">
          <span style="float: left">播放列表</span>
          <span style="float: left;font-size: 12px">共{{musicPlayQueue.length}}首歌</span>
          <span style="float: right"><el-link :underline="false" v-show="true"><i
            class="iconfont icon-shanchuwubiankuang" @click="closeMusicPlayQueue"></i></el-link></span>
        </div>
      </template>
      <div>
        <el-table :data="musicPlayQueue"
                  style="width: 100%"
                  max-height="460"
                  size="small"
                  :stripe=true
                  :show-header=false
                  v-loading="loading"
                  element-loading-text="Loading..."
                  element-loading-svg-view-box="-10, -10, 50, 50">
          <el-table-column type="index" width="35"/>
          <el-table-column prop="audioName" width="230">
            <template slot-scope="scope">
              <el-link :underline="false" v-show="true" v-text="musicPlayQueue[scope.$index].audioName"
                       @click="getPlayMusic(musicPlayQueue[scope.$index].hash,musicPlayQueue[scope.$index].albumId)"></el-link>
            </template>
          </el-table-column>
          <el-table-column prop="timeLength" width="35"/>
          <el-table-column prop="icon" width="40">
            <template slot-scope="scope">
              <el-link :underline="false" v-show="true"><i class="iconfont icon-shanchu"
                                                           @click="removeMusic(scope.$index)"></i></el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
  import header from "../layout/Header";
  import footer from "../layout/Footer";
  import menu from "../layout/Menu";

  export default {
    components: {
      'v-header': header,
      'v-footer': footer,
      'v-menu': menu
    },
    name: "PlayMusic",
    data() {
      return {
        windowHeight: window.screen.availHeight-250,
        hash: '',
        albumId: '',
        nowMusicIndex: 0,
        musicInfo: {},
        //音乐
        audio: {
          url: '',
          playing: false,
          nowTime: 0,//单位是秒
          timeLength: 0,//单位是毫秒,1s=1000ms
          showTimeLength: '',
          showNowTime: '0:00',
          currentMusicLyric: [],
          lyricIndex: 0,
        },
        //播放列表
        musicPlayQueue: [],
        //进度条
        sliderTime: 0,
        display: 'none',
        loading: false,
      }
    },
    created() {
      document.title = '音乐播放';
    },
    mounted() {
      this.onPause();
      this.musicPlayQueue = this.$route.query.musicPlayQueue;
      console.log(this.musicPlayQueue);
      this.getPlayMusic(this.$route.query.hash, this.$route.query.albumId);
      this.hash = this.$route.query.hash;
      this.albumId = this.$route.query.albumId;
      this.audio.playing = true;
      this.getMusicPlayQueue();
      this.onPlay();
    },
    methods: {
      //分享复制
      copyShare() {
        const clipboardObj = navigator.clipboard;
        let url = window.location.protocol + '//' + window.location.host + "/#" + this.$route.path + "?hash=" + this.hash + "&albumId=" + this.albumId;
        let url1 = '我发现一首好听的歌快来听听吧！播放地址：' + url;
        clipboardObj.writeText(url1);
        this.$message.success('已复制到粘贴板，快去分享给你的朋友吧！')
      },
      //跳转到评论
      toPlayMusicComment() {
        let routeUrl = this.$router.resolve({
          path: '/playMusicComment',
          query: {
            hash: this.hash,
            albumId: this.albumId
          }
        });
        window.open(routeUrl.href, '_blank');
      },
      //添加喜欢歌曲
      likeMusic(hash, albumId) {
        if (sessionStorage.getItem("token") != null) {
          this.$axios({
            method: 'post',
            url: '/user/likeMusic',
            dataType: 'json',
            crossDomain: true,
            headers: {
              Authentication: sessionStorage.getItem("token")
            },
            data: {
              hash: hash,
              albumId: albumId
            }
          }).then(res1 => {
            if (res1.data.msgCode === '-1') {
              this.$message({
                message: '登录过期，请重新登录',
                type: 'warning'
              });
              this.$router.push('/login');
            } else {
              if (this.musicInfo.likeFlag === 1) {
                this.musicInfo.likeFlag = 0;
              } else {
                this.musicInfo.likeFlag = 1;
              }
            }
          })
        } else {
          this.$confirm('您还未登录，请先登录后添加喜欢', '提示', {
            confirmButtonText: '确定',
            type: 'info'
          }).then(() => {
            this.$router.push('/login')
          })
        }
      },
      //判断当前歌曲在musicPlayQueue中的哪个位置
      getNowPlayMusicIndexFromMusicPlayQueue(hash, albumId) {
        for (let i = 0; i < this.musicPlayQueue.length; i++) {
          if (hash === this.musicPlayQueue[i].hash && albumId === this.musicPlayQueue[i].albumId) {
            this.nowMusicIndex = i;
          }
        }
      },
      //下一首歌
      nextMusic() {
        this.onPause();
        this.getNowPlayMusicIndexFromMusicPlayQueue(this.hash, this.albumId);
        this.nowMusicIndex++;
        if (this.nowMusicIndex >= this.musicPlayQueue.length) {
          this.nowMusicIndex = 0
        }
        this.getPlayMusic(this.musicPlayQueue[this.nowMusicIndex].hash, this.musicPlayQueue[this.nowMusicIndex].albumId);
        this.onPlay();
      },
      //上一首歌
      lastMusic() {
        this.onPause();
        this.getNowPlayMusicIndexFromMusicPlayQueue(this.hash, this.albumId);
        this.nowMusicIndex--;
        if (this.nowMusicIndex < 0) {
          this.nowMusicIndex = this.musicPlayQueue.length - 1;
        }
        this.getPlayMusic(this.musicPlayQueue[this.nowMusicIndex].hash, this.musicPlayQueue[this.nowMusicIndex].albumId);
        this.onPlay();
      },
      //移除播放列表音乐
      removeMusic(index) {
        console.log(index);
        this.$delete(this.musicPlayQueue, index)
      },
      //打开播放列表
      openMusicPlayQueue() {
        this.display = 'block';
      },
      //关闭播放列表
      closeMusicPlayQueue() {
        this.display = 'none';
      },
      //获取播放列表
      getMusicPlayQueue() {
        this.loading = true;
        this.$axios({
          method: 'post',
          url: '/redis/getMusicPlayQueue'
        }).then(res => {
          console.log(res.data.data.info);
          this.musicPlayQueue = res.data.data.info;
          this.loading = false;
        })
      },
      //跳转播放
      changeCurrentTime(index) {
        this.onPause();
        this.$refs.audio.currentTime = this.audio.timeLength * (index / 100);
        this.onPlay();
      },
      //播放遇到错误
      onError() {
        this.$alert('因版权原因该首歌本网站未收录,点击确认关闭该网页', '温馨提示', {
          confirmButtonText: '确定',
          callback: action => {
            window.opener=null;
            window.open('','_self');
            window.close();
          }
        });
      },
      //播放
      onPlay() {
        this.$refs.audio.play();
        this.audio.playing = true;
      },
      //暂停
      onPause() {
        this.$refs.audio.pause();
        this.audio.playing = false;
      },
      //获取音乐信息
      getPlayMusic(hash, albumId) {
        this.$axios({
          method: 'get',
          url: '/kugou/playMusic/' + hash + "/" + albumId,
          headers: {
            token: sessionStorage.getItem("token")
          }
        }).then(res => {
          this.musicInfo = res.data.data.info;
          this.audio.timeLength = Math.floor(this.musicInfo.timeLength / 1000);//转化成秒
          let musicLength = this.audio.timeLength;
          let min = Math.floor(musicLength / 60);
          let second = Math.floor(musicLength - (min * 60));
          if (second < 10) {
            second = '0' + second
          }
          this.audio.showTimeLength = min + ':' + second;
          console.log(this.musicInfo);
          //对歌词处理
          let lyricArr = res.data.data.info.lyrics.split('[').slice(1); // 先以[进行分割
          let lrcObj = {};
          lyricArr.forEach(item => {
            let arr = item.split(']');	// 再分割右括号
            // 时间换算成秒
            let m = parseInt(arr[0].split(':')[0]);
            let s = parseInt(arr[0].split(':')[1]);
            arr[0] = m * 60 + s;
            if (arr[1] !== '\n') { // 去除歌词中的换行符
              lrcObj[arr[0]] = arr[1];
            }
          });
          this.audio.currentMusicLyric = lrcObj;
          console.log(this.audio.currentMusicLyric);
          this.hash = hash;
          this.albumId = albumId;
        });
      },
      //每秒更新进度条
      onTimeUpdate(res) {
        this.audio.nowTime = res.target.currentTime;
        this.sliderTime = (this.audio.nowTime / this.audio.timeLength) * 100;
        let musicLength = this.audio.nowTime;
        let min = Math.floor(musicLength / 60);
        let second = Math.floor(musicLength - (min * 60));
        if (second < 10) {
          second = '0' + second
        }
        this.audio.showNowTime = min + ':' + second;
        if (this.audio.showNowTime === this.audio.showTimeLength) {
          this.audio.playing = false;
        }
        for (let currentMusicLyricKey in this.audio.currentMusicLyric) {
          if (currentMusicLyricKey == Math.floor(this.audio.nowTime)) {
            this.audio.lyricIndex = currentMusicLyricKey;
            let element = document.getElementById(this.audio.lyricIndex);
            element.scrollIntoView({
              block: 'center'
            });
          }
        }

      },
      onLoadedMetaData() {

      }
    }
  }
</script>

<style scoped>

  /*播放列表样式*/
  .box-card {
    position: fixed;
    right: 10%;
    bottom: 80px;
    z-index: 4;
    display: none;
    width: 350px;
    height: 500px
  }

  .card-header {
    height: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .playMusicBody {
    width: 100%;
    height: 100%;
  }

  .cover {
    width: 100%;
    height: 100%;
    position: absolute;
    background-color: #000000;
    background-color: rgba(0, 0, 0, 0.99);
    z-index: -1;
    opacity: .6;
  }

  .cover1 {
    width: 100%;
    height: 100%;
    position: absolute;
    background-repeat: no-repeat;
    background-size: cover;
    overflow: hidden;
    z-index: -2;
    filter: blur(90px);
  }

  .musicBody {
    width: 1000px;
  }

  /deep/ .el-scrollbar {
    height: 100%;
  }

  /deep/ .el-scrollbar__wrap {
    overflow-x: hidden;
  }

  .player {
    position: fixed;
    bottom: 0;
    width: 100%;
    background-color: #cfcfcf;
    height: 80px;
    border-radius: 8px 8px 0 0;
    line-height: 80px;
  }

  .disablePlayer {
    line-height: 30px;
  }

  /deep/ .el-slider__button {
    width: 12px;
    height: 12px;
  }

  .playIconSize {
    font-size: 40px;
  }

  .iconSize {
    font-size: 20px;
  }

  .textColor_1 {
    color: #ffffff;
  }

  .textColor_2 {
    color: #cfcfcf;
  }

  .lyric {

    font-size: 10px;
  }

  .each {
    height: 30px;
    line-height: 30px;
    text-align: center;
  }

  .choose {
    height: 30px;
    line-height: 30px;
    font-size: 20px;
    color: #01e5ff;
    opacity: 1;
  }


  /*修改滚动条样式*/
  ::-webkit-scrollbar {
    width: 3px;
    height: 1px;
  }

  /*滑块部分*/
  ::-webkit-scrollbar-thumb {
    background-color: #eee;
  }

  /*轨道部分*/
  ::-webkit-scrollbar-track {
    background-color: #333;
  }

  /deep/ .el-card__body {
    padding: 0;
  }

  /deep/ .el-table .cell {
    padding: 5px;
    text-align: center;
  }

</style>
